package cn.admin.configcenter.registry.common.util;

import cn.admin.remoting.Connection;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

public class ConfigUtil {

    public static String generateHostId(Connection connection) {
        return connection == null ? null :
                connection.getRemoteAddress() + ":" + connection.getRemotePort();
    }

    public static String getUUID() {
        String uuid = UUID.randomUUID().toString();
        return uuid.replaceAll("-","");
    }

    public static void writeConfigFile(File confFile,String content,String encoding) throws IOException {

        File tmpConfFile = new File(confFile.getAbsolutePath() + ".tmp");
        SimpleDateFormat sdf_bakRevision = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        File bakFile = new File(confFile.getAbsoluteFile() + "."
                + sdf_bakRevision.format(new Date()));

        FileOutputStream stream = new FileOutputStream(tmpConfFile);
        try {
            stream.write(content.getBytes(encoding));
            stream.flush();
        } finally {
            if (stream != null) {
                stream.close();
            }
        }

        confFile.renameTo(bakFile);
        tmpConfFile.renameTo(confFile);

    }

}
